import React, { Component } from 'react'
import { connect } from 'react-redux'
import Axios from "axios"
//引入组件

import { NavLink } from 'react-router-dom';
import RouterView from '../router';
import MyTabbar from '../components/MyTabbar';
import { SearchBar, WhiteSpace, WingBlank, Toast } from 'antd-mobile';
import ProductList from '../components/ProductList';


export class List extends Component {
  componentWillMount() {

    console.log('this.props', this.props);

    if (!this.props.list.length) {
      this.props.getList();
    }



  }
  render() {
    return (
      <div className="page">
        <div className="content">

          <WingBlank><div className="sub-title">Normal</div></WingBlank>
          <SearchBar placeholder="搜索商品" maxLength={8}
            onSubmit={value => this.props.searchList(value)}
            onClear={value => console.log(value, 'onClear')}
            onFocus={() => console.log('onFocus')}
            onBlur={() => console.log('onBlur')}
            onCancel={() => console.log('onCancel')}
            showCancelButton
            onChange={this.onChange}
          />
          <WhiteSpace />

          <NavLink to="/list/listA">列表A</NavLink> <NavLink to="/list/listB">列表B</NavLink>
          <div>
            <RouterView routes={this.props.child}></RouterView>
          </div>
          {/* 产品列表 */}
          <ProductList {...this.props}></ProductList>
        </div>

        <MyTabbar {...this.props}></MyTabbar>
      </div>
    )
  }

}

const mapStateToProps = (state) => {
  return {
    ...state
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    // 数据库存数据
    getList() {
      console.log('数据开始加载' + new Date().getTime())
      Toast.loading('数据加载中...');
      dispatch(() => {

        Axios.get("/get/list").then(res => {
          dispatch({ type: "SET_LIST", data: res.data.data });
          Toast.hide();
          console.log('数据加载完毕' + new Date().getTime())
        })
      })
    },
    setList(data) {
      dispatch({ type: "SET_LIST", data: data })
    },
    searchList(keyword) {
      console.log('数据开始加载' + new Date().getTime())
      Toast.loading('数据加载中...');
      dispatch(() => {

        Axios.post('/api/search', { keyword: keyword }).then((res) => {
          console.log('dispatch search', res);
          dispatch({ type: "SET_LIST", data: res.data.data });
          Toast.hide();
          console.log('数据加载完毕' + new Date().getTime())
        })
      })
    }


  }
}

export default connect(mapStateToProps, mapDispatchToProps)(List)
